from datetime import datetime, timedelta
import json
import os
import random
import string
import jwt
from flask import jsonify, request, render_template

# 管理员密码
TOKEN_ADMIN_PASSWORD = "admin123"  # 请修改为安全的密码

# JWT密钥
JWT_SECRET = "tiktok-miaoshou-token-manager"  # 请修改为安全的密钥

class TokenManager:
    def __init__(self):
        self.admin_password = TOKEN_ADMIN_PASSWORD
        self.jwt_secret = JWT_SECRET
        
    def generate_token_code(self, length=16):
        """生成随机授权码前缀"""
        characters = string.ascii_letters + string.digits
        return ''.join(random.choice(characters) for _ in range(length))

    def get_expire_time(self, token):
        """获取授权码过期时间"""
        try:
            payload = jwt.decode(token, self.jwt_secret, algorithms=['HS256'])
            return datetime.fromtimestamp(payload['exp'])
        except:
            return None

    def verify_token(self, token):
        """验证授权码（JWT格式）"""
        expire_time = self.get_expire_time(token)
        if expire_time is None:
            return False
        return datetime.now() <= expire_time
    
    def verify_admin_password(self, password):
        """验证管理员密码"""
        if password == self.admin_password:
            # 生成管理员token
            admin_token = jwt.encode({
                'exp': datetime.utcnow() + timedelta(hours=24),
                'type': 'admin'
            }, self.jwt_secret, algorithm='HS256')
            
            return {
                'code': 0,
                'token': admin_token
            }
        else:
            return {
                'code': 1,
                'msg': '密码错误'
            }
    
    def verify_admin_token(self, token):
        """验证管理员token"""
        try:
            payload = jwt.decode(token, self.jwt_secret, algorithms=['HS256'])
            return payload.get('type') == 'admin'
        except:
            return False
    
    def create_token(self, expire_days, remark):
        """创建新的授权码（JWT格式）"""
        # 生成随机前缀
        prefix = self.generate_token_code(8)
        
        # 创建JWT payload
        expire_time = datetime.now() + timedelta(days=expire_days)
        payload = {
            'prefix': prefix,
            'exp': expire_time.timestamp(),
            'remark': remark,
            'created_at': datetime.now().timestamp()
        }
        
        # 生成JWT token
        token = jwt.encode(payload, self.jwt_secret, algorithm='HS256')
        
        # 保存到历史记录
        self._save_token_history(token, expire_time, remark)
        
        return {
            'code': token,
            'expire_time': expire_time.strftime('%Y-%m-%d'),
            'remark': remark,
            'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'is_valid': True
        }
    
    def _save_token_history(self, token, expire_time, remark):
        """保存token历史记录（仅用于展示）"""
        history_file = 'data/token_history.json'
        try:
            if os.path.exists(history_file):
                with open(history_file, 'r') as f:
                    history = json.load(f)
            else:
                history = []
            
            history.append({
                'code': token,
                'remark': remark,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            })
            
            with open(history_file, 'w') as f:
                json.dump(history, f, indent=4)
        except:
            # 历史记录保存失败不影响主要功能
            pass
    
    def get_token_list(self):
        """获取授权码历史列表"""
        try:
            if os.path.exists('data/token_history.json'):
                with open('data/token_history.json', 'r') as f:
                    tokens = json.load(f)
                # 添加有效性状态
                for token in tokens:
                    try:
                        token['expire_time'] = self.get_expire_time(token['code']).strftime('%Y-%m-%d')
                        token['is_valid'] = self.verify_token(token['code'])
                    except:
                        token['expire_time'] = None
                        token['is_valid'] = False
                return tokens
            return []
        except:
            return []

# 路由处理函数
def init_token_routes(app, token_manager):
    @app.route('/token')
    def token_page():
        return render_template('token.html')

    @app.route('/verify_admin', methods=['POST'])
    def verify_admin():
        data = request.get_json()
        password = data.get('password')
        return jsonify(token_manager.verify_admin_password(password))

    @app.route('/generate_token', methods=['POST'])
    def generate_token():
        # 验证管理员token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                'code': 1,
                'msg': '未提供管理员token'
            })
        
        if not token_manager.verify_admin_token(auth_header):
            return jsonify({
                'code': 1,
                'msg': '管理员token无效或已过期'
            })
        
        data = request.get_json()
        expire_days = int(data.get('expire_days', 30))
        remark = data.get('remark', '')
        
        token_info = token_manager.create_token(expire_days, remark)
        return jsonify({
            'code': 0,
            'msg': '授权码生成成功',
            'data': token_info
        })

    @app.route('/list_tokens')
    def list_tokens():
        # 验证管理员token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({
                'code': 1,
                'msg': '未提供管理员token'
            })
        
        if not token_manager.verify_admin_token(auth_header):
            return jsonify({
                'code': 1,
                'msg': '管理员token无效或已过期'
            })
        
        tokens = token_manager.get_token_list()
        return jsonify({
            'code': 0,
            'data': tokens
        })



if __name__ == '__main__':
    token_manager = TokenManager()
    token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwcmVmaXgiOiJrNWN6SkRkYiIsImV4cCI6MTc0Mjk4ODIzMy42NDY1NjgsInJlbWFyayI6Ilx1NmQ0Ylx1OGJkNSIsImNyZWF0ZWRfYXQiOjE3NDI5MDE4MzMuNjQ2NTg0fQ.lCSRS8LXXtH6IUZdobQxpLB4m55321yzOBgvxUmZMFI'
    print(token_manager.verify_token(token))
